package com.digdes.calendar.gwt.client.widget;

import com.digdes.calendar.gwt.client.dto.EventDTOImpl;
import com.digdes.calendar.gwt.client.dto.EventParticipantDTOImpl;
import com.digdes.calendar.gwt.client.dto.PlaceDTOImpl;
import com.digdes.calendar.gwt.client.dto.UserDTOImpl;
import com.digdes.calendar.gwt.client.service.CalendarService;
import com.digdes.calendar.gwt.client.service.CalendarServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.datepicker.client.DateBox;


//import eu.maydu.gwt.validation.client.DefaultValidationProcessor;
//import eu.maydu.gwt.validation.client.ValidationProcessor;

import java.util.*;


public class CreateEventDialog extends DialogBox {

    // AutoComplite(facebook)
    List<String> itemsSelected = new ArrayList<String>();

    public Button save = new Button("Сохранить");

    private CreateFileDialog addFileDialog;
    private CreateParticipantDialog addUserDialog;
    private CreatePlace addPlaceDialog;
    //  ValidationProcessor validator = new DefaultValidationProcessor();


    public String[] hours = new String[]{"9", "10", "11", "12", "13", "14", "15", "16", "17", "18"};

    private final CalendarServiceAsync calendarservice = GWT.create(CalendarService.class);
    ListBox placelist = new ListBox();
    ListBox userlist = new ListBox();
    List<Object> choices = new ArrayList<Object>(0);

    TextBox textbox = new TextBox();
    final ListBox choicesListBox = new ListBox();


    DateBox dateStart = new DateBox();
    DateBox dateFinish = new DateBox();

    ListBox timeStart = new ListBox();
    ListBox timeFinish = new ListBox();
    // для ссылки на планировщик.
    Plan plan;

    List<PlaceDTOImpl> places = new ArrayList<PlaceDTOImpl>(0);
    List<UserDTOImpl> users = new ArrayList<UserDTOImpl>(0);
    PlaceDTOImpl selectPlace;
    List<UserDTOImpl> selectUsers = new ArrayList<UserDTOImpl>(0);
    TextArea descr;
    CheckBox isAllDay;
    TextBox nameEvent;
    //private SuggestOracle suggestions;

    public CreateEventDialog() {
    }

    public CreateEventDialog(CreateFileDialog addFile, CreateParticipantDialog addUser, Plan scheduler, CreatePlace addPlace) {

        final BulletList list = new BulletList();
        list.setStyleName("token-input-list-facebook");
        final ListItem item = new ListItem();
        item.setStyleName("token-input-input-token-facebook");
        final TextBox itemBox = new TextBox();
        itemBox.getElement().setAttribute("style", "outline-color: -moz-use-text-color; outline-style: none; outline-width: medium;");
        final SuggestBox box = new SuggestBox(getSuggestions2(), itemBox);


        box.getElement().setId("suggestion_box");
        item.add(box);
        list.add(item);


        VerticalPanel vp = new VerticalPanel();
        HorizontalPanel hp2 = new HorizontalPanel();
        HorizontalPanel hp = new HorizontalPanel();


        this.plan = scheduler;
        setText("Создание события");

        this.addUserDialog = addUser;
        this.addFileDialog = addFile;
        this.addPlaceDialog = addPlace;
        setAnimationEnabled(true);
        setGlassEnabled(true);

        // Create buttons

        Button cl = new Button("Закрыть");
        Button helper = new Button("Планировщик");

        Button addFileBtn = new Button("+Файл");

        final Button addUserBtn = new Button("Создать");
        final Button createPlace = new Button("Добавить новое место");

        addFileBtn.setSize("100px", "30px");
        addUserBtn.setSize("100px", "30px");
        cl.setSize("100px", "30px");
        helper.setSize("100px", "30px");
        save.setSize("100px", "30px");

        // Create time

        DateTimeFormat dateFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_LONG);
        // DateBox dateBox = new DateBox();
        dateStart.setFormat(new DateBox.DefaultFormat(dateFormat));
        dateFinish.setFormat(new DateBox.DefaultFormat(dateFormat));
        // dateBox.setSize("155px", "30px");


        // Create textArea

        descr = new TextArea();
        descr.setVisibleLines(5);
        descr.setWidth("400px");


        // Create checkbox

        isAllDay = new CheckBox("Событие на весь день");


        // Create textbox

        nameEvent = new TextBox();
        nameEvent.setSize("200px", "30px");

        // Create facebook form

        itemBox.addKeyDownHandler(new KeyDownHandler() {
            public void onKeyDown(KeyDownEvent event) {
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                    // only allow manual entries with @ signs (assumed email addresses)
                    if (itemBox.getValue().contains("@"))
                        deselectItem(itemBox, list);
                }
                // handle backspace
                if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE) {
                    if ("".equals(itemBox.getValue().trim())) {
                        ListItem li = (ListItem) list.getWidget(list.getWidgetCount() - 2);
                        Paragraph p = (Paragraph) li.getWidget(0);
                        if (itemsSelected.contains(p.getText())) {
                            itemsSelected.remove(p.getText());
                            GWT.log("Removing selected item '" + p.getText() + "'", null);
                            GWT.log("Remaining: " + itemsSelected, null);
                        }
                        list.remove(li);
                        itemBox.setFocus(true);
                    }
                }
            }
        });

        box.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
            public void onSelection(SelectionEvent selectionEvent) {
                deselectItem(itemBox, list);
            }
        });

        // Button createPlace
        createPlace.setVisible(false);

        createPlace.addClickHandler(new ClickHandler() {
            //          @Override
            public void onClick(ClickEvent event) {

                addPlaceDialog.center();
                addPlaceDialog.show();


            }
        });


        // Create listbox and set Place from BD


        placelist.setSize("155px", "30px");

        placelist.setVisibleItemCount(1);
        calendarservice.getAllPlace(new AsyncCallback<Set<PlaceDTOImpl>>() {
            //@Override
            public void onFailure(Throwable throwable) {
                GWT.log("Can not get places.");
                //To change body of implemented methods use File | Settings | File Templates.
            }

            //@Override
            public void onSuccess(Set<PlaceDTOImpl> placeDTOs) {
                places.clear();
                GWT.log("Size placese:" + placeDTOs.size());
                for (PlaceDTOImpl place : placeDTOs) {
                    placelist.addItem(place.getAddress());
                    places.add(place);
                    GWT.log("Place:" + place);
                }
                placelist.setSelectedIndex(0);
                if (places != null && places.size() != 0) {
                    int index = placelist.getSelectedIndex();
                    if (index >= 0 && index < places.size()) {
                        selectPlace = places.get(placelist.getSelectedIndex());
                    }
                }
            }
        });


        // Create listbox "time" to choose time on panel
        dateStart.setValue(new Date());
        dateFinish.setValue(new Date());

        timeStart.setVisibleItemCount(1);
        timeFinish.setVisibleItemCount(1);

        for (String hour : hours) {
            timeStart.addItem(hour);
            timeFinish.addItem(hour);
        }

        timeStart.setSelectedIndex(0);
        timeFinish.setSelectedIndex(9);

        // Добавление отработки check на весь день
        isAllDay.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
            public void onValueChange(ValueChangeEvent<Boolean> booleanValueChangeEvent) {
                if (booleanValueChangeEvent.getValue()) {
                    timeStart.setSelectedIndex(0);
                    timeStart.setEnabled(false);
                    timeFinish.setSelectedIndex(9);
                    timeFinish.setEnabled(false);
                } else {
                    timeStart.setEnabled(true);
                    timeFinish.setEnabled(true);
                }
            }
        });

        /*// Добавление событий на кнопки.
        save.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                EventDTOImpl newEvent = new EventDTOImpl();

                // установка дат события.
                newEvent.setDateStart(new Date(dateStart.getValue().getTime()
                        + 3600000 * (timeStart.getSelectedIndex() + 9)));
                newEvent.setDateFinish(new Date(dateFinish.getValue().getTime()
                        + 3600000 * (timeFinish.getSelectedIndex() + 9)));
                // установка имени и описания события и других свойств.
                if (nameEvent.getText().isEmpty()) {
                    newEvent.setNameEvent("Без названия");
                } else newEvent.setNameEvent(nameEvent.getText());
                newEvent.setDescription(descr.getText());
                newEvent.setAllDay(isAllDay.getValue());
                newEvent.setNeedNotice(true);


                // Автора пока приходится брать так...
                newEvent.setAuthor(selectUsers.get(0));
                *//* Set<EventParticipantDTOImpl> participants = new HashSet<EventParticipantDTOImpl>(0);
                for (UserDTOImpl user : selectUsers) {
                    EventParticipantDTOImpl participant = new EventParticipantDTOImpl();
                    participant.setParticipant(user);

                    participant.setStatus(7);
                    participants.add(participant);
                }
                newEvent.setParticipants(participants);*//*
                newEvent.setPlace(selectPlace);
                // ПОДУМАТЬ НАД СОЗДАНИЕМ КАСТОМНЫХ МЕСТ
                //  newEvent.setMyPlace("Новое место");

                calendarservice.saveEvent(newEvent, new AsyncCallback<EventDTOImpl>() {
                    public void onFailure(Throwable caught) {
                    }

                    public void onSuccess(EventDTOImpl result) {

                    }

                });
                CreateEventDialog.this.hide();
                // НУЖНО ЕЩЕ ДОБАВИТЬ ОБНОВЛЕНИЕ КАЛЕНДАРЯ
            }
        });*/


        addFileBtn.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                addFileDialog.center();
                addFileDialog.show();
            }
        });
        addUserBtn.setVisible(true);

        addUserBtn.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                addUserDialog.center();
                addUserDialog.show();
            }
        });
        createPlace.addClickHandler(new ClickHandler() {
            //@Override
            public void onClick(ClickEvent event) {
                addPlaceDialog.center();
                addPlaceDialog.show();
            }
        });

        helper.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {

                CreateEventDialog.this.hide();


                if (selectPlace != null) {
                    List<Object> recordsScheduler = new ArrayList<Object>(0);
                    recordsScheduler.add(selectPlace);
                    plan.choiceDialog.setRecordsPlace(recordsScheduler);
                }

                plan.getMainPanel().dateStart.setValue(dateStart.getValue());
                plan.getMainPanel().dateFinish.setValue(dateFinish.getValue());
                plan.getMainPanel().timeStart.setSelectedIndex(timeStart.getSelectedIndex());
                plan.getMainPanel().timeFinish.setSelectedIndex(timeFinish.getSelectedIndex());
                plan.drawScheduler(0);

                RootPanel.get("main").setVisible(false);
                RootPanel.get("scheduler").setVisible(true);
            }
        });

        cl.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                CreateEventDialog.this.hide();
            }
        });

        placelist.addChangeHandler(new ChangeHandler() {
            public void onChange(ChangeEvent changeEvent) {
                createPlace.setVisible(true);
                selectPlace = places.get(placelist.getSelectedIndex());
            }
        });

        choicesListBox.setVisible(false);
        choicesListBox.setWidth("300px");
        //  addUserBtn.setVisible(false);


        textbox.setText("Введите имя");

        choicesListBox.setVisibleItemCount(3);
        textbox.addKeyUpHandler(new KeyUpHandler() {
            //@Override
            public void onKeyUp(KeyUpEvent event) {
                choicesListBox.setVisible(true);
                addUserBtn.setVisible(true);


                String text = textbox.getValue();
                for (int i = 0; i < choicesListBox.getItemCount(); i++) {
                    if (choicesListBox.getValue(i).regionMatches(true, 0, text, 0, text.length())) {
                        choicesListBox.setSelectedIndex(i);
                        break;
                    }
                }

            }
        });
        choicesListBox.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent clickEvent) {
                textbox.setText(choicesListBox.getValue(choicesListBox.getSelectedIndex()));
                choicesListBox.setVisible(false);
                addUserBtn.setVisible(false);
            }
        });


        // Show dialogbox with all components


        AbsolutePanel timePanel = new AbsolutePanel();
        timePanel.setSize("300px", "150px");
        timePanel.add(new HTML("Начало события"), 30, 0);
        timePanel.add(dateStart, 30, 20);
        timePanel.add(timeStart, 200, 20);
        timePanel.add(new HTML("Окончание события"), 30, 50);
        timePanel.add(dateFinish, 30, 70);
        timePanel.add(timeFinish, 200, 70);

        vp.setSize("330px", "400px");
        vp.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
        vp.add(helper);
        vp.add(new HTML("<br>"));
        vp.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT);
        vp.add(new HTML("Название события"));
        vp.add(nameEvent);
        vp.add(new HTML("Описание"));
        vp.add(descr);
        vp.add(new HTML("<br>"));
        vp.add(isAllDay);

        vp.add(timePanel);
        vp.add(new HTML("<br>"));
        vp.add(new HTML("Выберите место"));
        vp.add(new HTML("<br>"));

        hp2.add(placelist);
        hp2.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
        hp2.add(new HTML("<tab>"));
        hp2.add(createPlace);
        vp.add(hp2);

        vp.add(new HTML("<br>"));
        vp.add(new HTML("Добавьте пользователя или создайте нового"));
        vp.add(new HTML("<br>"));

        vp.add(list);
        //vp.getElement().setAttribute("onclick", "document.getElementById('suggestion_box').focus()");
        box.setFocus(true);


        vp.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
        vp.add(addUserBtn);
        vp.add(addFileBtn);
        vp.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT);

        vp.add(hp);

        hp.add(save);
        hp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
        hp.add(cl);
        vp.add(hp);

        setWidget(vp);
    }


    //  public CreateFileDialog getAddFile() {
    //    return addFileDialog;
    //  }

    public void setAddFileDialog(CreateFileDialog addFileDialog) {
        this.addFileDialog = addFileDialog;
    }

    public void showDialog() {
        calendarservice.getAllPlace(new AsyncCallback<Set<PlaceDTOImpl>>() {
            public void onFailure(Throwable throwable) {
                GWT.log("Can not get places.");
            }

            public void onSuccess(Set<PlaceDTOImpl> placeDTOs) {
                places.clear();
                placelist.clear();
                GWT.log("Size placese:" + placeDTOs.size());

                long selectID = 0;
                if (selectPlace == null)
                    selectID = -1;
                else
                    selectID = selectPlace.getId();

                for (PlaceDTOImpl place : placeDTOs) {
                    placelist.addItem(place.getAddress());
                    places.add(place);
                    if (place.getId() == selectID)
                        placelist.setSelectedIndex(places.size());

                    GWT.log("Place:" + place);
                }


            }
        });
        CreateEventDialog.this.center();
    }

    public void show() {
        super.show();
    }

    public List<PlaceDTOImpl> getPlaces() {
        return places;
    }

    public void setPlaces(List<PlaceDTOImpl> places) {
        this.places = places;
    }

    public List<UserDTOImpl> getUsers() {
        return users;
    }

    public void setUsers(List<UserDTOImpl> users) {
        this.users = users;
    }

//    public CreateParticipantDialog getAddUserDialog() {
    //      return addUserDialog;
    //   }

    public void setAddUserDialog(CreateParticipantDialog addUserDialog) {
        this.addUserDialog = addUserDialog;
    }


    /*   private void setupValidation() {
validator = new DefaultValidationProcessor(showcaseMessages);
popupDesc = new PopupDescription(showcaseMessages);
FocusAction focusAction = new FocusAction();

validator.addValidators("positiveInteger",
     new IntegerValidator(integerPositiveTextBox, 0, Integer.MAX_VALUE)
             .addActionForFailure(focusAction)
             .addActionForFailure(new StyleAction("validationFailedBorder"))
     //.addActionForFailure(new TextAction(errorLabel))
);


popupDesc.addDescription("positiveIntegerHelp", integerPositiveTextBox);

validator.addValidators("integerInRangeMinus5000Plus5000",
     new IntegerValidator(integerMinus5000To5000TextBox, -5000, 5000)
             .addActionForFailure(focusAction)
             .addActionForFailure(new StyleAction("validationFailedBorder"))
);

popupDesc.addDescription("integerInRangeMinus5000Plus5000Help", integerMinus5000To5000TextBox);

validator.addValidators("anyInteger",
     new IntegerValidator(integerTextBox3)
             .addActionForFailure(focusAction)
             .addActionForFailure(new StyleAction("validationFailedBorder"))
);

popupDesc.addDescription("anyIntegerHelp", integerTextBox3);


validator.addValidators("stringLengthSmaller5",
     new StringLengthValidator(stringLengthSmaller5TextBox, 0, 4)
             .addActionForFailure(focusAction)
             .addActionForFailure(new StyleAction("validationFailedBorder"))
);

popupDesc.addDescription("stringLengthSmaller5Help", stringLengthSmaller5TextBox);


validator.addValidators("stringLengthBetween2And5",
     new StringLengthValidator(stringLengthBetween2And5TextBox, 2, 5)
             .addActionForFailure(focusAction)
             .addActionForFailure(new StyleAction("validationFailedBorder"))
);

popupDesc.addDescription("stringLengthBetween2And5Help", stringLengthBetween2And5TextBox);

validator.addValidators("notEmpty",
     new NotEmptyValidator(notEmptyTextBox)
             .addActionForFailure(focusAction)
             .addActionForFailure(new StyleAction("validationFailedBorder"))
);

popupDesc.addDescription("notEmptyHelp", notEmptyTextBox);

RegularExpressionValidator regex = new RegularExpressionValidator(regexValidateEntryTextBox, new ValidatorConfigurationSource() {

 /*
    *  Use of a dynamically configured RegularExpressionValidator.
    *
    *  Normally you would only have to pass the regex string "(a|b)*" in this
    *  case into the constructor. But if you want dynamic setting of the
    *  regular expression you need to provide an implementation for this
    *  interface
    *
    */
    /*
            public String getConfigurationValue() {
                String regex = regexEntryTextBox.getText();
                return regex;
            }

        }, "regexNotMatched");

        validator.addValidators("enterRegExedText", regex
                .addActionForFailure(new StyleAction("validationFailedBorder"))
                .addActionForFailure(focusAction)
        );

        popupDesc.addDescription("regexText.description", regexValidateEntryTextBox);

        validator.addGlobalAction(new DisclosureTextAction(allErrorsPanel, "redText"));


        transValidator = new ValidationProcessor();
        transValidator.addValidators("string1", new UpperCaseTransformer(uppercaseTextBox));
        transValidator.addValidators("string2", new TrimmedUpperCaseTransformer(trimmedUppercaseTextBox));
        transValidator.addValidators("caesar1", new CaesarEncryptionTransformer(caesarTextBox, 1));

    }   */

    private void deselectItem(final TextBox itemBox, final BulletList list) {
        if (itemBox.getValue() != null && !"".equals(itemBox.getValue().trim())) {
            /** Change to the following structure:
             * <li class="token-input-token-facebook">
             * <p>What's New Scooby-Doo?</p>
             * <span class="token-input-delete-token-facebook">x</span>
             * </li>
             */

            final ListItem displayItem = new ListItem();
            displayItem.setStyleName("token-input-token-facebook");
            Paragraph p = new Paragraph(itemBox.getValue());

            displayItem.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent clickEvent) {
                    displayItem.addStyleName("token-input-selected-token-facebook");
                }
            });
            Span span = new Span("x");
            span.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent clickEvent) {
                    removeListItem(displayItem, list);
                }
            });

            displayItem.add(p);
            displayItem.add(span);
            // hold the original value of the item selected

            GWT.log("Adding selected item '" + itemBox.getValue() + "'", null);
            itemsSelected.add(itemBox.getValue());
            GWT.log("Total: " + itemsSelected, null);

            list.insert(displayItem, list.getWidgetCount() - 1);
            itemBox.setValue("");
            itemBox.setFocus(true);
        }
    }

    private void removeListItem(ListItem displayItem, BulletList list) {
        GWT.log("Removing: " + displayItem.getWidget(0).getElement().getInnerHTML(), null);
        itemsSelected.remove(displayItem.getWidget(0).getElement().getInnerHTML());
        list.remove(displayItem);
    }


    // Method for get all users from bd
    private SuggestOracle getSuggestions2() {
        final MultiWordSuggestOracle oracle2 = new MultiWordSuggestOracle();
        final List<String> itemsSelected2 = new ArrayList<String>();

        calendarservice.getUsers(new AsyncCallback<Set<UserDTOImpl>>() {
            //@Override
            public void onFailure(Throwable throwable) {

            }

            //@Override
            public void onSuccess(Set<UserDTOImpl> userDTOs) {
                users.clear();
                for (UserDTOImpl user : userDTOs) {
                    userlist.addItem(user.getName());
                    users.add(user);
                }
                for (UserDTOImpl user : userDTOs) {

                    itemsSelected2.add(user.getName());
                    oracle2.add(user.getName() + " " + user.getSurname());
                    selectUsers.add(user);
                }
            }
        });

        return oracle2;
    }

    /*public EventDTOImpl newEvent() {
EventDTOImpl newEvent = new EventDTOImpl();

     // установка дат события.
     newEvent.setDateStart(new Date(dateStart.getValue().getTime()
             + 3600000 * (timeStart.getSelectedIndex() + 9)));
     newEvent.setDateFinish(new Date(dateFinish.getValue().getTime()
             + 3600000 * (timeFinish.getSelectedIndex() + 9)));
     // установка имени и описания события и других свойств.
      if(nameEvent.getText().isEmpty()){
         newEvent.setNameEvent("Без названия");
      }else newEvent.setNameEvent(nameEvent.getText());

     newEvent.setDescription(descr.getText());
     newEvent.setAllDay(isAllDay.getValue());
     newEvent.setNeedNotice(true);

      if(nameEvent.getText().isEmpty()){
          newEvent.setNameEvent("Без названия");
      }
     newEvent.setPlace(selectPlace);

     // Автора пока приходится брать так...
     newEvent.setAuthor(selectUsers.get(0));
    *//* Set<EventParticipantDTOImpl> participants = new HashSet<EventParticipantDTOImpl>(0);
                EventParticipantDTOImpl participant = new EventParticipantDTOImpl();
                    for(UserDTOImpl user:selectUsers){

                    participant.setParticipant(user);
                    participant.setEvent(newEvent);
                    participant.setStatus(0);
                    participants.add(participant);
                }
               newEvent.setParticipants(participants);*//*

        return newEvent;
    }
*/
    public void saveEvent() {
        EventDTOImpl newEvent = new EventDTOImpl();

        // установка дат события.
        newEvent.setDateStart(new Date(dateStart.getValue().getTime()
                + 3600000 * (timeStart.getSelectedIndex() + 9)));
        newEvent.setDateFinish(new Date(dateFinish.getValue().getTime()
                + 3600000 * (timeFinish.getSelectedIndex() + 9)));
        // установка имени и описания события и других свойств.
        if (nameEvent.getText().isEmpty()) {
            newEvent.setNameEvent("Без названия");
        } else newEvent.setNameEvent(nameEvent.getText());
        newEvent.setDescription(descr.getText());
        newEvent.setAllDay(isAllDay.getValue());
        newEvent.setNeedNotice(true);


        // Автора пока приходится брать так...
        newEvent.setAuthor(selectUsers.get(0));
        /* Set<EventParticipantDTOImpl> participants = new HashSet<EventParticipantDTOImpl>(0);
        for (UserDTOImpl user : selectUsers) {
            EventParticipantDTOImpl participant = new EventParticipantDTOImpl();
            participant.setParticipant(user);

            participant.setStatus(7);
            participants.add(participant);
        }
        newEvent.setParticipants(participants);*/
        newEvent.setPlace(selectPlace);
        // ПОДУМАТЬ НАД СОЗДАНИЕМ КАСТОМНЫХ МЕСТ
        //  newEvent.setMyPlace("Новое место");

        calendarservice.saveEvent(newEvent, new AsyncCallback<EventDTOImpl>() {
            public void onFailure(Throwable caught) {
            }

            public void onSuccess(EventDTOImpl result) {

            }

        });
        CreateEventDialog.this.hide();
        // НУЖНО ЕЩЕ ДОБАВИТЬ ОБНОВЛЕНИЕ КАЛЕНДАРЯ
    }
}
    